package cn.itcast.hiss.server.order;

import cn.hutool.core.util.StrUtil;
import cn.itcast.hiss.server.mapper.GoodsMapper;
import cn.itcast.hiss.server.util.SpringContextHolder;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/*
 * @author miukoo
 * @description 库存更新
 * @date 2023/8/23 19:12
 * @version 1.0
 **/
public class UpdateStockServiceTask implements JavaDelegate {

    @Override
    public void execute(DelegateExecution execution) {
        ApplicationContext applicationContext = SpringContextHolder.getApplicationContext();
        GoodsMapper goodsMapper = applicationContext.getBean(GoodsMapper.class);

        // 获取事务管理器
        DataSourceTransactionManager transactionManager = applicationContext.getBean(DataSourceTransactionManager.class);
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        transactionDefinition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        // 开启事务
        TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
        try {
            // 获取仓库入库的数据
            String storeContent = (String) execution.getVariable("storeContent");
            if (StrUtil.isNotEmpty(storeContent)) {
                String[] ids = storeContent.split(",");
                for (String id : ids) {
                    String temp[] = id.split("#");
                    goodsMapper.updateStock(Integer.valueOf(temp[0]), Integer.valueOf(temp[1]));
                }
            }
            transactionManager.commit(status);// 提交事务
        }catch (Exception e){
            e.printStackTrace();
            transactionManager.rollback(status);// 回滚事务
        }
    }

}